/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 * */

// AmzServer - Tototoy's server model.
// Author: tonyjobmails@gmail.com (tonyhack).
//
// Define class ConditionVariable.
//

#ifndef __CONDITION__VARIABLE__H
#define __CONDITION__VARIABLE__H

#include <sys/time.h>

#include "mutex.h"

namespace amz {

class ConditionVariable : public noncopyable {
 public:
  ConditionVariable() {
    pthread_condattr_t attr;
    pthread_condattr_init(&attr);
    int return_code = pthread_cond_init(&this->condition_, &attr);
    pthread_condattr_destroy(&attr);

    ConditionVariable::ErrorLog("ConditionVariable::ConditionVariable", return_code);
  }
  ~ConditionVariable() {
    pthread_cond_destroy(&this->condition_);
  }

  void Wait(Mutex *mutex) {
    pthread_cond_wait(&this->condition_, &(mutex->mutex_));
  }

  // timeout_in_msecs < 0: wait forever
  // timeout_in_msecs >= 0: wait timeout_in_msecs msec
  bool Wait(Mutex *mutex, int timeout_in_msecs) {
    if(timeout_in_msecs < 0) {
      this->Wait(mutex);
      return true;
    }

    struct timeval tv;
    gettimeofday(&tv, NULL);

    // add timeout
    tv.tv_sec += timeout_in_msecs / 1000;
    tv.tv_usec += (timeout_in_msecs % 1000) * 1000;

    int million = 1000000;
    if(tv.tv_usec >= million) {
      tv.tv_sec += tv.tv_usec / million;
      tv.tv_usec %= million;
    }   

    // convert timeval to timespec
    struct timespec ts;
    ts.tv_sec = tv.tv_sec;
    ts.tv_nsec = tv.tv_usec * 1000;
    int return_code = pthread_cond_timedwait(&this->condition_, &mutex->mutex_, &ts);

    if(return_code != 0) {
      ConditionVariable::ErrorLog("ConditionVariable::Wait", return_code);
      return false;
    }

    return true;
  }

  void Signal() {
    ConditionVariable::ErrorLog("ConditionVariable::Signal", pthread_cond_signal(&this->condition_));
  }

  void Broadcast() {
    ConditionVariable::ErrorLog("ConditionVariable::Broadcast", pthread_cond_broadcast(&this->condition_));
  }

 private:
  void ErrorLog(const char* context, int error) {
    if(error != 0) {
      LOG(ERROR) << context
                 << " error:"
                 << strerror(error);
    }
  }

  pthread_cond_t condition_;
};

}  // namespace amz

#endif  // __CONDITION__VARIABLE__H

